package com.qxy.practice.concurrent;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author : 戚欣扬
 * @Description : //      v4   对Condtion的灵活运用，指定唤醒线程   A 5->B 10->C 15 loop 10
 */
public class ThreadOrder {
    private int flag  = 1;
    private Lock lock = new ReentrantLock();
    private Condition key = lock.newCondition();
    private Condition key1 = lock.newCondition();
    private Condition key2 = lock.newCondition();
    private Condition key3 = lock.newCondition();

    /**
     * print 1-5
     */
    public void print5(){
        lock.lock();
        try {
            while(flag!=1){
                key.await();
            }
            for (int i = 0; i < 5; i++) {
                System.out.println(Thread.currentThread().getName()+":"+(i+1));
            }
            flag = 2;
            key2.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * print 1-10
     */
    public void print10(){
        lock.lock();
        try {
            while(flag!=2){
                key.await();
            }
            for (int i = 0; i < 10; i++) {
                System.out.println(Thread.currentThread().getName()+":"+(i+1));
            }
            flag = 3;
            key2.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }

    /**
     * print 1-15
     */
    public void print15(){
        lock.lock();
        try {
            while(flag!=3){
                key.await();
            }
            for (int i = 0; i < 15; i++) {
                System.out.println(Thread.currentThread().getName()+":"+(i+1));
            }
            flag = 1;
            key2.signalAll();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }
    /**
     * main
     */
    public static void main(String[] args) {

        ThreadOrder threadOrder = new ThreadOrder();
        for (int i = 0; i < 10; i++) {
            new Thread(()->{
                threadOrder.print5();
            },"A").start();
            new Thread(()->{
                threadOrder.print10();
            },"B").start();
            new Thread(()->{
                threadOrder.print15();
            },"C").start();
        }

    }

}


